<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/17
 * Time: 9:35
 * 淘宝客优惠券
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\CommissionRebate;
use app\common\model\CouponCollectRecord;
use app\common\model\FundsRecord;
use app\common\model\OrderTbk;
use app\common\model\PromotionPosition;
use think\Db;
use think\Request;

class Tbk extends Api {
	protected $noNeedRight = ['*'];
	protected $topClient = null;
	protected $adzoneid = '';
	protected $noNeedLogin = ['tbksettlementorder', 'tbkneworder'];
	
	private $tbkAppkey='24703018',
		$tbkSecret='69f271db4adf88ad166fe06e21dc4b09',
		$taobaoAdzoneid='156126650';
	
	public function __construct(Request $request = null)
	{
		parent::__construct($request);
		vendor('taobao.TopSdk');
		$this->topClient = new \TopClient();
		
		//查找商户是否配置淘宝客信息，没有使用默认信息
		$config = Db::name('taobaoConfig')
			->find();
		
		if($config) {
			$appkey = $config['taobao_appkey'];
			$secretKey = $config['taobao_appsecret'];
			$adzoneId = $config['taobao_adzoneid'];
		} else {
			$appkey = $this->tbkAppkey;
			$secretKey = $this->tbkSecret;
			$adzoneId = $this->taobaoAdzoneid;
		}
		
		$this->topClient->appkey = $appkey;
		$this->topClient->secretKey = $secretKey;
		$this->adzoneid = $adzoneId;
	}
	
	/**
	 * 淘宝客物料下行-导购(推荐商品)
	 */
	public function dgOptimusMaterial () {
		$page = input('post.page', 1, 'intval');
		
		$time = time();
		$where = [
			'ai.position' => 5,
			'ai.begin_time' => ['elt', $time],
			'ai.end_time' => ['egt', $time],
		];
		
		
		$returnData['banner'] = Db::name('appIndex')->alias('ai')
			->join('appClass ac', 'ai.app_class_id = ac.id', 'left')
			->where($where)
			->field('ai.position, ai.app_image, ai.name, ai.url, ai.param_id, ai.login, ac.ios_class, ac.android_class')
			->order(['ai.sort' => 'ASC'])
			->select();
		
		//商品分类
		$where['ai.position'] = 12;
		$returnData['category'] = Db::name('appIndex')->alias('ai')
			->join('appClass ac', 'ai.app_class_id = ac.id', 'left')
			->where($where)
			->field('ai.position, ai.app_image, ai.name, ai.url, ai.param_id, ai.login, ac.ios_class, ac.android_class')
			->order(['ai.sort' => 'ASC'])
			->select();
		
		$returnData['goods'] = [];
		
		$c = $this->topClient;
		$req = new \TbkDgOptimusMaterialRequest();
		$req->setPageSize("20");
		$req->setAdzoneId($this->adzoneid);
		$req->setPageNo($page);
		$req->setMaterialId("9660");
//		$req->setDeviceValue("xxx");
//		$req->setDeviceEncrypt("MD5");
//		$req->setDeviceType("IMEI");
//		$req->setContentId("323");
//		$req->setContentSource("xxx");
		
		$resp = $c->execute($req);
		$res = json_encode($resp);
		$result = \GuzzleHttp\json_decode($res, true);
		if(isset($result['result_list']['map_data'])) {
			
			$coupons = $result['result_list']['map_data'];
			$goods = [];
			if(!empty($coupons)) {
				$rebateModel = new CommissionRebate();
				$config = $rebateModel->where([
					'rebate_type' => $rebateModel::REBATE_TYPE_TBK
				])->find();
				foreach ($coupons as $coupon) {
					$commissionAmount = 0;
					if($config) {
						if($config['self_type'] == 1) {
							$commissionAmount = floor($coupon['commission_rate']*$coupon['zk_final_price']*$config['self'])/100;
						} else {
							$commissionAmount = $config['self'];
						}
					}
					
					$goods[] = [
						'goods_img' => $this->checkUrl($coupon['pict_url']),
						'goods_title' => $coupon['title'],
						'goods_id' => $coupon['item_id'],
						'shop_title' => '',
						'sale_number' => $coupon['volume'],
						'coupon_info' => '',
						'coupon_amount' => floatval($coupon['coupon_amount']),
						'coupon_after_price' => floatval($coupon['zk_final_price']-$coupon['coupon_amount']),
						'coupon_remain_count' => '',
						'coupon_total_count' => $coupon['coupon_total_count'],
						'goods_price' => floatval($coupon['zk_final_price']),
						'commission_amount' => floatval($commissionAmount),
						'commission_rate' => $coupon['commission_rate'],
						'coupon_click_url' => $this->checkUrl($coupon['coupon_click_url']),
						'item_url' => $this->checkUrl($coupon['click_url']),
						'small_images' => [],
						'user_type' => $coupon['user_type'],
						'goods_type' => $coupon['user_type'] == 1 ? 'tmall' : 'taobao',
						'exchange_tips' => $coupon['coupon_amount'] > 0 ? '确定使用抵扣券兑换该现金券吗？' : '',
						'isPinGou' => '',
						'planId' => '',
						'requestId' => '',
					];
				}
			}
			$returnData['goods'] = $goods;
		}
		
		$this->success('查询成功', $returnData);
	}
	
	
	/**
	 *  通用物料搜索API（导购）
	 */
	public function dgMaterialOptional () {
		$keyword = input('post.keyword', '女装');
		$page = input('post.page', 1, 'intval');
		$sort = input('post.sort', 'tk_rate_des');
		$c = $this->topClient;
		$req = new \TbkDgMaterialOptionalRequest();
		$req->setAdzoneId($this->adzoneid); //mm_xxx_xxx_xxx的第三位
		
//		$req->setStartDsr("10");//店铺dsr评分，筛选高于等于当前设置的店铺dsr评分的商品0-50000之间
//		$req->setPageSize("20"); //页大小，默认20，1~100
		$req->setPageNo($page); //第几页，默认：１
//		$req->setPlatform("1"); //链接形式：1：PC，2：无线，默认：１
//		$req->setEndTkRate("1234"); //淘客佣金比率上限，如：1234表示12.34%
//		$req->setStartTkRate("1234"); //淘客佣金比率下限，如：1234表示12.34%
//		$req->setEndPrice("10"); //折扣价范围上限，单位：元
//		$req->setStartPrice("10"); //折扣价范围下限，单位：元
//		$req->setIsOverseas("false"); //是否海外商品，设置为true表示该商品是属于海外商品，设置为false或不设置表示不判断这个属性
//		$req->setIsTmall("true"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
		
		
		$req->setSort($sort); //排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price）
//		$req->setItemloc("杭州"); //	所在地
//		$req->setCat("16,18"); //后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
		$req->setQ($keyword); //查询词
//		$req->setMaterialId("2836"); //	官方的物料Id(详细物料id见：https://tbk.bbs.taobao.com/detail.html?appId=45301&postId=8576096)，不传时默认为2836
		$req->setHasCoupon("true"); //是否有优惠券，设置为true表示该商品有优惠券，设置为false或不设置表示不判断这个属性
//		$req->setIp("13.2.33.4"); //ip参数影响邮费获取，如果不传或者传入不准确，邮费无法精准提供
//		$req->setNeedFreeShipment("true"); //是否包邮，true表示包邮，空或false表示不限
//		$req->setNeedPrepay("true"); //是否加入消费者保障，true表示加入，空或false表示不限
//		$req->setIncludePayRate30("true"); //成交转化是否高于行业均值
//		$req->setIncludeGoodRate("true"); //好评率是否高于行业均值
//		$req->setIncludeRfdRate("true"); //退款率是否低于行业均值
//		$req->setNpxLevel("2"); //牛皮癣程度，取值：1:不限，2:无，3:轻微
//		$req->setEndKaTkRate("1234"); //KA媒体淘客佣金比率上限，如：1234表示12.34%
//		$req->setStartKaTkRate("1234"); //KA媒体淘客佣金比率下限，如：1234表示12.34%
//		$req->setDeviceEncrypt("MD5"); //设备号加密类型：MD5
//		$req->setDeviceValue("xxx"); //设备号加密后的值
//		$req->setDeviceType("IMEI"); //设备号类型：IMEI，或者IDFA，或者UTDID
		$resp = $c->execute($req);
		$res = json_encode($resp);
		$result = \GuzzleHttp\json_decode($res, true);
//		dump($result);die;
		if(isset($result['result_list']['map_data'])) {
			$coupons = $result['result_list']['map_data'];
			$goods = [];
			if(!empty($coupons)) {
				$rebateModel = new CommissionRebate();
				$config = $rebateModel->where([
					'rebate_type' => $rebateModel::REBATE_TYPE_TBK
				])->find();
				
				foreach ($coupons as $coupon) {
					$couponAmount = 0;
					if($coupon['coupon_info']) {
						preg_match('/减(.*?)元/is', $coupon['coupon_info'] , $r);
						$couponAmount = isset($r[1]) ? sprintf('%.2f', $r[1])  : 0;
					}
					
					$coupon['commission_rate'] = $coupon['commission_rate']/10000;
					$commissionAmount = 0;
					if($config) {
						if($config['self_type'] == 1) {
							$commissionAmount = floor($coupon['commission_rate']*$coupon['zk_final_price']*$config['self']*100)/100;
						} else {
							$commissionAmount = $config['self'];
						}
					}
					$goods[] = [
						'goods_img' => $this->checkUrl($coupon['pict_url']),
						'goods_title' => $coupon['title'],
						'goods_id' => $coupon['num_iid'],
						'shop_title' => $coupon['shop_title']?:'',
						'sale_number' => $coupon['volume'],
						'coupon_info' => $coupon['coupon_info'],
						'coupon_amount' => floatval($couponAmount),
						'coupon_after_price' => floatval($coupon['zk_final_price']-$couponAmount),
						'coupon_remain_count' => $coupon['coupon_remain_count'],
						'coupon_total_count' => $coupon['coupon_total_count'],
						'goods_price' => floatval($coupon['zk_final_price']),
						'commission_amount' => floatval($commissionAmount),
						'commission_rate' => $coupon['commission_rate'],
						'coupon_click_url' => isset($coupon['coupon_share_url']) ? $this->checkUrl($coupon['coupon_share_url']):'',
						'item_url' => $this->checkUrl($coupon['item_url']),
						'user_type' => $coupon['user_type'],
						'goods_type' => $coupon['user_type'] == 1 ? 'tmall' : 'taobao',
						'small_images' => isset($coupon['small_images']['string']) ? $coupon['small_images']['string'] : [],
						'exchange_tips' => $couponAmount > 0 ? '确定使用抵扣券兑换该现金券吗？' : '',
						'isPinGou' => '',
						'planId' => '',
						'requestId' => '',
					];
				}
			}
			$this->success('查询成功', $goods);
		} else {
			$this->success('查询成功', []);
		}
	}
	
	
	/**
	 * 兑换优惠券
	 * @param $goodsId
	 * @param $amount
	 * @return array
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function exchange($goodsId, $amount){
		!$goodsId && $this->error('商品ID不能为空');
		
		//扣除券金额
		$userId = $this->auth->id;
		$user = Db::name('user')->find($userId);
		if($amount > 0 && $user['voucher_balance'] < $amount) {
			$this->error('抵扣券不足，当前抵扣券【'.$user['voucher_balance'].'】');
		}
		
		Db::startTrans();
		try {
			if($amount > 0) {
				$userRes = Db::name('user')->where(['id' => $userId])->setDec('voucher_balance', $amount);
				if(!$userRes) {
					throw new Exception('扣除抵扣券出错');
				}
				
				//记录资金流水
				$logModel = new FundsRecord();
				$logRes = $logModel->addRecord($userId, $amount, $user['voucher_balance'], $logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_LESS, $logModel::TYPE_VOUCHER_EXCHANGE);
				if(!$logRes) {
					throw new Exception('记录资金流水出错');
				}
			}
			
			//添加用户领券记录
			$recordRes = Db::name('CouponCollectRecord')
				->insert([
					'user_id' => $userId,
					'goods_id' => $goodsId,
					'create_time' => time()
				]);
			if(!$recordRes) {
				throw new Exception('添加领取记录出错');
			}
			
			
			
			Db::commit();
			return [
				'status' => true,
				'info' => ''
			];
			
		} catch (Exception $e) {
			Db::rollback();
			return [
				'status' => false,
				'info' => $e->getMessage()
			];
		}
		
		
	}
	
	
	/**
	 * 检查URL
	 * @param $url
	 * @return string
	 */
	public function checkUrl($url) {
		if($url && !preg_match('/^http/', $url)){
			return 'https:'.$url;
		} else {
			return $url;
		}
	}
	
	
	/**
	 * 匹配淘宝订单号
	 */
	public function pregOrder(){
		$orderNo = input('post.order_no');
		!$orderNo && $this->error('订单号不能为空');
		
		$model = new OrderTbk();
		$row = $model->where(['taobaoTradeParentId' => $orderNo])->find();
		!$row && $this->error('订单不存在');
		
		if($row['user_id']) {
			$this->error('该订单已匹配其它用户');
		}
		
		$userId = $this->auth->id;
		//查找该用户是否领过这个商品
		$record = Db::name('couponCollectRecord')
			->where([
				'goods_id' => $row['auctionId'],
				'user_id' => $userId,
				'type' => CouponCollectRecord::TYPE_TBK,
				'status' => CouponCollectRecord::STATUS_W,
				'create_time' => ['elt', strtotime($row['createTime'])]
			])
			->find();
		if(!$record) {
			$this->error('你没有领取过此商品优惠券');
		}
		
		$res = Db::name('orderTbk')
			->where(['id' => $row['id']])
			->update([
				'user_id' => $userId,
				'status' => $model::STATUS_W
			]);
		if($res) {
			$this->success('匹配成功，等待返利');
		} else {
			$this->error('匹配出错');
		}
		
	}
	
	/**
	 * @param $text
	 * @param $url
	 * @param string $logo
	 * @return mixed
	 */
	public function taobaoTbkTpwdCreate ($text, $url, $logo = '') {
		$c = $this->topClient;
		$req = new \TbkTpwdCreateRequest();
//		$req->setUserId("123");
		$req->setText($text);
		$req->setUrl($url);
		$logo && $req->setLogo($logo);
		$req->setExt("{}");
		$resp = $c->execute($req);
		$res = json_encode($resp);
		$result = \GuzzleHttp\json_decode($res, true);
		return $result;
	}
	
	
	/**
	 * 查询当天付款成功的订单
	 */
	public function tbkNewOrder() {
		if($this->request->isAjax()) {
			$postData = $this->request->request();
			$orders = isset($postData['data']['paymentList']) ? $postData['data']['paymentList']: [];
			if($orders) {
				$model = new OrderTbk();
				foreach($orders as $order) {
					$where['taobaoTradeParentId'] = $order['taobaoTradeParentId'];
					
					$row = Db::name('orderTbk')
						->where($where)
						->find();
					if($row) {
						$res = $model->allowField(true)->save($order, ['id' => $row['id']]);
					} else {
						$order['status'] = $model::STATUS_P;
						$res = $model->allowField(true)->isUpdate(false)->insert($order);
					}
					
				}
			}
			$this->success('操作成功');
		}
	}
	
	/**
	 * 处理淘宝客已经结算的订单
	 */
	public function tbkSettlementOrder () {
		if($this->request->isAjax()) {
			$postData = $this->request->request();
			$orders = isset($postData['data']['paymentList']) ? $postData['data']['paymentList']: [];
			if($orders) {
				$model = new OrderTbk();
				foreach($orders as $order) {
					$where['taobaoTradeParentId'] = $order['taobaoTradeParentId'];
					//查找成交的订单数据
					$row = Db::name('orderTbk')
						->where($where)
						->find();
					
					if($row && $row['status'] == $model::STATUS_W) {
						//如果数据存在，且状态为待结算，更改状态为待返利
						$data['status'] = $model::STATUS_S;
						$res = $model->allowField(true)->save($data, ['id' => $row['id']]);
					} else {
						$order['status'] = $model::STATUS_S;
						$res = $model->allowField(true)->isUpdate(false)->insert($order);
					}
					
				}
			}
		}
		$this->success('操作成功');
	}
	
}
